package com.payment.web.controller.system;

import com.payment.common.base.AjaxResult;
import com.payment.common.page.TableDataInfo;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.ExcelUtil;
import com.payment.common.utils.StringUtils;
import com.payment.framework.web.base.BaseController;
import com.payment.system.domain.OrderGg;
import com.payment.system.service.IOrderGgService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 光谷订单对账 信息操作处理
 *
 * @author fuzhili
 * @date 2019-09-18
 */
@Controller
@RequestMapping("/system/orderGg")
public class OrderGgController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(OrderGgController.class);
    private String prefix = "system/orderGg";

    @Autowired
    private IOrderGgService orderGgService;

    @RequiresPermissions("system:orderGg:view")
    @GetMapping()
    public String orderGg() {
        return prefix + "/orderGg";
    }

    /**
     * 查询光谷订单对账列表
     */
    @RequiresPermissions("system:orderGg:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrderGg orderGg) {
        startPage();
        List<OrderGg> list = orderGgService.selectOrderGgList(orderGg);
        return getDataTable(list);
    }

    /**
     * 新增畅捷订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }


    /**
     * 导出光谷订单对账列表
     */
    @RequiresPermissions("system:orderGg:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(OrderGg orderGg) {
        orderGg.setPayPro(new BigDecimal("1"));
        List<OrderGg> list = orderGgService.selectOrderGgList(orderGg);
        ExcelUtil<OrderGg> util = new ExcelUtil<OrderGg>(OrderGg.class);
        return util.exportExcel(list, "orderGg");
    }

    /**
     * 导入
     */
    @PostMapping("upload")
    @ResponseBody
    public AjaxResult upload(MultipartFile file, String uploadTime, MultipartFile file1) {
        if (file == null || StringUtils.isEmpty(uploadTime) || file1 == null) {
            return error("获取参数失败");
        }
        uploadTime = DateUtils.timeStamp2Date(uploadTime, DateUtils.YYYY_MM_DD);
        //删除对账时间订单信息
        orderGgService.deleteOrderGuangGuByDateTime(uploadTime);
        List<OrderGg> list = new ArrayList<>();
        List<Workbook> workbookList = new ArrayList<>();
        try {
            workbookList.add(WorkbookFactory.create(file.getInputStream()));
            workbookList.add(WorkbookFactory.create(file1.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        Integer type = 0;
        for (Workbook workbook : workbookList) {
            //有多少个sheet
            int sheets = workbook.getNumberOfSheets();
            for (int i = 0; i < sheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                //获取多少行
                int rows = sheet.getPhysicalNumberOfRows();
                OrderGg order = null;
                //遍历每一行，注意：第 0 行为标题
                for (int j = 1; j < rows; j++) {
                    try {
                        order = new OrderGg();
                        //获得第 j 行
                        Row row = sheet.getRow(j);
                        Row title = sheet.getRow(0); //获取标题
                        for (int l = 0; l < title.getPhysicalNumberOfCells(); l++) {
                            if (title.getCell(l).getStringCellValue().trim().equals("订单时间")) {
                                if (row.getCell(l) != null && row.getCell(l).getStringCellValue().length() <= 32) {
                                    order.setInsertTime(row.getCell(l).getStringCellValue());
                                } else {
                                    continue;
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("通道编号") || title.getCell(l).getStringCellValue().trim().equals("渠道编号")) {
                                if (row.getCell(l) != null) {
                                    order.setAcqCode(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("渠道名称")) {
                                if (row.getCell(l) != null) {
                                    order.setAcqName(row.getCell(l).getStringCellValue() + "");
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("用户id")) {
                                if (row.getCell(l) != null) {
                                    order.setAcqUserId(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("商户交易订单号")) {
                                if (row.getCell(l) != null) {
                                    order.setOrderId(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("支付订单号")) {
                                if (row.getCell(l) != null) {
                                    order.setAcqOrderId(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("姓名")) {
                                if (row.getCell(l) != null) {
                                    order.setUserName(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("证件号")) {
                                if (row.getCell(l) != null) {
                                    order.setIdCard(row.getCell(l).getStringCellValue() + "");
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("银行卡号")) {
                                if (row.getCell(l) != null) {
                                    order.setBankNumber(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("支付金额")) {
                                if (row.getCell(l) != null) {
                                    order.setOrderAmount(new BigDecimal(row.getCell(l).getStringCellValue()));
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("用户支付费率")) {
                                if (row.getCell(l) != null) {
                                    order.setPayRate(new BigDecimal(row.getCell(l).getStringCellValue()));
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("订单状态")) {
                                if (row.getCell(l) != null) {
                                    order.setOrderStatus(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("用户笔数费")) {
                                if (row.getCell(l) != null) {
                                    //分润提现/无卡出款 的订单不保存
                                    BigDecimal pro = new BigDecimal(row.getCell(l).getStringCellValue());
                                    order.setPayPro(pro);
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("银行名称")) {
                                if (row.getCell(l) != null) {
                                    order.setBankName((row.getCell(l).getStringCellValue()));
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("订单类型") || (title.getCell(l).getStringCellValue().trim().equals("订单状态") && type == 0)) {
                                //到最后一列 退出当前循环
                                break;
                            }
                        }
                        order.setOrderType(type);

                        //只保存成功订单
                        if (order.getOrderStatus() != null && "成功".equals(order.getOrderStatus())) {
                            if (type == 0) {
                                BigDecimal rate = order.getPayRate();
                                if (rate != null && (rate.compareTo(new BigDecimal("0.65")) == 0 )) {
                                    continue;
                                } else {
                                    list.add(order);
                                }
                            } else {
                                BigDecimal pro = order.getPayPro();
                                if (pro != null && (pro.compareTo(new BigDecimal("3")) == 0||pro.compareTo(new BigDecimal("2")) == 0)) {
                                    continue;
                                } else {
                                    list.add(order);;
                                }
                            }

                        }
                    } catch (Exception e) {
                        log.error("畅捷订单导入异常=" + e.getMessage());

                    }
                }
            }
            type=1;
        }


        return orderGgService.orderGuangGuRecordNew(list);


    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        OrderGg order = orderGgService.selectOrderGgById(id);
        mmap.put("userName", order.getUserName());
        mmap.put("userId", order.getAcqUserId());
        mmap.put("bankNumber", order.getBankNumber());
        String insertTime = DateUtils.timeStamp2Date(order.getInsertTime(), DateUtils.YYYY_MM_DD);
        mmap.put("insertTime", insertTime);
        return prefix + "/details";
    }

    /**
     * 详情
     *
     * @param bankNumber
     * @param insertTime
     * @param userName
     * @param userId
     * @return
     */
    @PostMapping("/listByBankNumber")
    @ResponseBody
    public TableDataInfo ByBankAccountList(String bankNumber, String insertTime, String userName, String userId) {
        startPage();
        List<OrderGg> list = orderGgService.selectOrderListByBankNumber(insertTime, userId, userName, bankNumber);
        return getDataTable(list);
    }


}
